<?php

declare(strict_types=1);

namespace App\Model\Ocpc;

use App\Helpers\RedisUtil;
use Hyperf\DbConnection\Model\Model;

/**
 *  OcpcBaidu
 */
class OcpcBaidu extends Model
{
    protected $table = 'ocpc_baidu';

    public const BAIDU_CHANNEL = 408;

    public const CHANNELS = [self::BAIDU_CHANNEL];

    static function addLog($params = [], $bizType = 1)
    {
        $oaid = $params['oaid'] ?? '00000000';
        $channel = $params['channel'] ?? self::CHANNELS[0];
        $ua = $params['ua'] ?? '';
        $os_version = '';
        if ($ua) {
            if (strpos($ua, 'Android') !== false) {//strpos()定位出第一次出现字符串的位置，这里定位为0
                preg_match("/(?<=Android )[\d\.]{1,}/", $ua, $version);
                //$platform['os_platform'] = 'Android';
                $os_version = $version[0];
            }
        }
        $data = [
            'mac_md5' => $params['mac_md5'] ?? '',
            'oaid' => $oaid,
            'mac1' => $params['mac1'] ?? '',
            'imei_md5' => $params['imei_md5'] ?? '',
            'os' => $params['os'] ?? '',
            'ip' => $params['ip'] ?? '',
            'client_ip' => $params['client_ip'] ?? '',
            'click_id' => $params['click_id'] ?? '',
            'android_id' => $params['android_id'] ?? '',
            'ua' => $params['ua'] ?? '',
            'os_version' => $os_version,
            'callback_url' => $params['callback_url'] ?? '',
            'biz_type' => $bizType,
            'channel' => $channel,
            'akeys' => $params['akeys'] ?? '',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];
        return  self::insertGetId($data);
    }

    /**
     * 处理查询
     * @param $info
     * @return array|\Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object
     */
    public static function handleSearch($info)
    {
        //oaid 查询
        if (isset($info['oaid']) && $info['oaid'] && substr($info['oaid'], 0, 8) != "00000000") {
            $res = self::where('oaid', $info['oaid'])
                ->where("channel", $info['channel'])
                ->orderBy('created_at', "desc")->first(['id', 'channel', 'callback_url','akeys']);
            if ($res) return $res->toArray();
        }
        return [];
    }

    public static function existsOaid($oaid,$channel)
    {
        return self::where('oaid', $oaid)->where('channel', $channel)->exists();
    }
}